package com.wh1200.mybatis.dao.tests

import com.wh1200.mybatis.dao.BaseTest
import com.wh1200.xmlless.test.model.SimpleStudent
import com.wh1200.xmlless.test.dao.StudentBaseMapperDAO
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import jakarta.annotation.Resource
import org.junit.jupiter.api.Test
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.jvm.javaField
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull

/**
 * eq
 *
 * @param property
 * @param value
 * @return
 */
private fun <T> QueryWrapper<T>.eq(property: KMutableProperty1<T, Int>, value: Int): QueryWrapper<T> {
  val tableInfo = TableInfoHelper.getTableInfo(property.javaField!!.declaringClass)
  val field = tableInfo.fieldList.first { it.property == property.name }
  return this.eq(field.column, value)
}

/**
 *
 * @author 吴昊
 * @date 2023/12/8 0:09
 * @since v4.0.0
 * @version 1.0
 */
class StudentBaseMapperDAOTest : BaseTest() {

  @Resource
  private lateinit var dao: StudentBaseMapperDAO

  @Test
  fun insert() {
    val st = SimpleStudent("1", "2")
    dao.insert(st)
  }

  @Test
  fun deleteById() {
    val st = SimpleStudent("1", "2")
    dao.insert(st)
    assertNotNull(dao.selectById("1"))
    dao.deleteById("1")
    assertNull(dao.selectById("1"))
  }

  @Test
  fun deleteByEntity() {
    val st = SimpleStudent("1", "2")
    dao.insert(st)
    assertNotNull(dao.selectById("1"))
    dao.deleteById(st)
    assertNull(dao.selectById("1"))
  }

  @Test
  fun findOneByQueryWrapper() {
    dao.insert(
        SimpleStudent(
            name = "张三",
            gender = 1
        )
    )
    val qw = Wrappers.query<SimpleStudent>()
        .eq("name", "张三")
        .eq("sex", 1)
    assertNotNull(dao.selectOne(qw))
  }

  @Test
  fun findListByQueryWrapper() {
    dao.insertAll(
        listOf(
            SimpleStudent(
                name = "李四",
                gender = 1
            ),
            SimpleStudent(
                name = "张三",
                gender = 1
            ),
            SimpleStudent(
                name = "王五",
                gender = 2
            ),
        )
    )
    val qw = Wrappers.query<SimpleStudent>()
        .eq(SimpleStudent::gender, 1)
    val list = dao.selectList(Page(0, 10), qw)
    assertEquals(2, list.size)
  }

}
